package com.zhouyibike.uu.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.AppKeyResult;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.LoginResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.XieyiActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.CodeUtils;
import com.zhouyibike.uu.utils.TextUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


public class LoginActivity extends BaseActivity implements View.OnClickListener{
    private ImageButton mBtnBack;
    private TextView mBtnTitle;

    private EditText et_phone,et_pwd;
    private Button btn_getcode,btn_login;
    private CheckBox cb_isagree;
    private Dialog yzmdialog;
    private String code;
    private MyHandler myHandler;
    private int resend=60;//重写发生倒计时
    TextView t1, t2, t3, t4, et;
    private TextView tv_xieyi;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        myHandler=new MyHandler();
        initView();
        initDailog();
        getMsg();
//        if(preferences.getString("token","").equals("")){
//            getMsg();
//        }else{
//            startActivity(new Intent(LoginActivity.this,MainActivity.class));
//            finish();
//        }
    }
    private void initView(){
        mBtnBack= (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle= (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("登录");
        mBtnBack.setOnClickListener(this);

        et_phone= (EditText) findViewById(R.id.et_loginactivity_phone);
        et_pwd= (EditText) findViewById(R.id.et_loginactivity_pwd);
        btn_getcode= (Button) findViewById(R.id.btn_loginactivity_getcode);
        btn_getcode.setOnClickListener(this);
        btn_login= (Button) findViewById(R.id.btn_loginactivity_login);
        btn_login.setOnClickListener(this);
        et_phone.addTextChangedListener(new EditTextWatcher());
        et_pwd.addTextChangedListener(new EditTextWatcher2());
        cb_isagree= (CheckBox) findViewById(R.id.rbtn_loginactivity_isagree);
        tv_xieyi= (TextView) findViewById(R.id.tv_agreement);
        tv_xieyi.setOnClickListener(this);
    }
    private void initDailog(){
        View view = LayoutInflater.from(this).inflate(
                R.layout.yzm_dialog, null);
        yzmdialog = new Dialog(this, R.style.loading_dialog);
        final ImageView iv_code= (ImageView) view.findViewById(R.id.iv_codedialog_img);
        LinearLayout ll_refresh= (LinearLayout) view.findViewById(R.id.ll_codedialog_refresh);
        ll_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_code.setImageBitmap(CodeUtils.getInstance().createBitmap(LoginActivity.this));
                code=CodeUtils.getInstance().getCode();
            }
        });
        iv_code.setImageBitmap(CodeUtils.getInstance().createBitmap(this));
        ImageView iv_dismis= (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yzmdialog.dismiss();
            }
        });
        code=CodeUtils.getInstance().getCode();

        t1 = (TextView) view.findViewById(R.id.t1);
        t2 = (TextView) view.findViewById(R.id.t2);
        t3 = (TextView) view.findViewById(R.id.t3);
        t4 = (TextView) view.findViewById(R.id.t4);
        et = (EditText) view.findViewById(R.id.editHide);
        et.addTextChangedListener(tw);

        yzmdialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        yzmdialog.setCancelable(true);
        yzmdialog.setCanceledOnTouchOutside(false);
        yzmdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        yzmdialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    }
    /**
     * 获取token 和appkey
     */
    private void getMsg(){
        Map<String, String> params = new HashMap<>();
        params.put("type", "3");
        showProgressDialog();
        addSubscription(apiStores.getKey(params),
                new ApiCallback<AppKeyResult>() {

                    @Override
                    public void onSuccess(AppKeyResult model) {
                        if(model.getStatus()==Config.SUCCESSCODE){
                            SharedPreferences.Editor edit=preferences.edit();
                            edit.putString("token",model.getData().getToken());
                            edit.putString("appKey",model.getData().getAppKey());
                            edit.putString("logo",model.getData().getLogo());
                            edit.commit();
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    /**
     * 获取验证码
     */
    private void getCode(){
        Map<String, String> params = new HashMap<>();
        params.put("mobile", et_phone.getText().toString());
        String sign=et_phone.getText().toString()+preferences.getString("appKey","");
        params.put("token", preferences.getString("token",""));
        params.put("sign", TextUtils.MD5(sign));
        showProgressDialog();
        addSubscription(apiStores.getVerifyCode(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if(model.getStatus()==Config.SUCCESSCODE){
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    /**
     * 登录
     */
    private void login(){
        Map<String, String> params = new HashMap<>();
        params.put("mobile", et_phone.getText().toString());
        String sign=et_phone.getText().toString()+preferences.getString("appKey","");
        params.put("token", preferences.getString("token",""));
        params.put("code", et_pwd.getText().toString());
        params.put("sign", TextUtils.MD5(sign));
        showProgressDialog();
        addSubscription(apiStores.login(params),
                new ApiCallback<LoginResult>() {

                    @Override
                    public void onSuccess(LoginResult model) {
                        if(model.getStatus()==Config.SUCCESSCODE||model.getStatus()==Config.NEEDPAY||model.getStatus()==Config.RENZHENG){
                            SharedPreferences.Editor edit=preferences.edit();
                            edit.putString("mobile",et_phone.getText().toString());
                            edit.putString("token",model.getData().getToken());
                            edit.putString("fullName",model.getData().getFullName());
                            edit.putString("headPicture",model.getData().getHeadPicture());
                            edit.putString("nickName",model.getData().getNickName());
                            edit.putString("status",model.getData().getStatus());
                            edit.putBoolean("hasPassword",model.getData().isHasPassword());
                            edit.putString("createTime",model.getData().getCreateTime());
                            edit.putString("lastLoginTime",model.getData().getLastLoginTime());
                            edit.putString("minAmountForRiding",model.getData().getMinAmountForRiding());
                            edit.putString("rechargeAmount",model.getData().getRechargeAmount());
                            edit.putString("incomeAmount",model.getData().getIncomeAmount());
                            edit.putString("totalAmount",model.getData().getTotalAmount());
                            edit.putString("extendStatus",model.getExtendStatus());
                            edit.commit();
//                            Intent intent=new Intent(LoginActivity.this,MainActivity.class);
//                            intent.putExtra("isfromlogin",true);
//                            startActivity(intent);
                            setResult(1);
                            finish();

                        }else{
                            toastShow(model.getMessage());
                            Log.e( "onFailure: ", model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                        Log.e( "onFailure: ", msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_loginactivity_getcode:
//                yzmdialog.show();
                myHandler.sendEmptyMessage(1);
                getCode();
                break;
            case R.id.btn_loginactivity_login:
                //手机号不为空，且为11位
                if (!TextUtils.isNullorEmpty(et_phone.getText().toString()) && Pattern.matches(Config.PHONEREGX, et_phone.getText().toString())) {
                    //验证码不为空
                    if (!TextUtils.isNullorEmpty(et_pwd.getText().toString())) {
                        if(cb_isagree.isChecked()) {
                            login();
                        }else{
                            toastShow("请同意用户注册协议!");
                        }
                    }else {
                        toastShow("验证码不能为空！");
                    }
                } else {
                    toastShow("请输入正确的手机号！");
                }
                break;
            case R.id.tv_agreement:
                startActivity(new Intent(this,XieyiActivity.class));
                break;
        }
    }
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(resend<=0){
                btn_getcode.setText("获取验证码");
                resend=60;
                btn_getcode.setEnabled(true);
            }else {
                btn_getcode.setEnabled(false);
                btn_getcode.setText("重新发送(" + resend + ")");
                resend--;
                myHandler.sendEmptyMessageDelayed(1, 1000);
            }
        }
    }
    class EditTextWatcher implements TextWatcher {

        public void afterTextChanged(Editable edt) {

            //手机号不为空，且为11位
            if (!TextUtils.isNullorEmpty(et_phone.getText().toString()) && Pattern.matches(Config.PHONEREGX, et_phone.getText().toString())) {
                if(btn_getcode.getText().toString().equals("获取验证码")){
                    btn_getcode.setEnabled(true);
                }else{
                    btn_getcode.setEnabled(false);
                }
                //验证码不为空
                if (!TextUtils.isNullorEmpty(et_pwd.getText().toString())) {
                    btn_login.setEnabled(true);  //提交按钮可点击
                }else {
                    btn_login.setEnabled(true);  //提交按钮bu可点击
                }
            } else {
                btn_login.setEnabled(true);  //提交按钮bu可点击
                btn_getcode.setEnabled(false);
            }
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

    }
    class EditTextWatcher2 implements TextWatcher {

        public void afterTextChanged(Editable edt) {

            //手机号不为空，且为11位
            if (!TextUtils.isNullorEmpty(et_phone.getText().toString()) && Pattern.matches(Config.PHONEREGX, et_phone.getText().toString())) {
//                btn_getcode.setEnabled(true);
                //验证码不为空
                if (!TextUtils.isNullorEmpty(et_pwd.getText().toString())) {
                    btn_login.setEnabled(true);  //提交按钮可点击
                }else {
                    btn_login.setEnabled(false);  //提交按钮bu可点击
                }
            } else {
                btn_login.setEnabled(false);  //提交按钮bu可点击
            }
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

    }
    String key = "";
    void setKey() {
        char[] arr = key.toCharArray();
        t1.setText("");
        t2.setText("");
        t3.setText("");
        t4.setText("");
        t1.setBackgroundResource(R.drawable.shape_input_area);
        t2.setBackgroundResource(R.drawable.shape_input_area);
        t3.setBackgroundResource(R.drawable.shape_input_area);
        t4.setBackgroundResource(R.drawable.shape_input_area);
        for (int i = 0; i < arr.length; i++) {
            if (i == 0) {
                t1.setText(String.valueOf(arr[0]));
                t1.setBackgroundResource(R.drawable.shape_input_ok);
            } else if (i == 1) {
                t2.setText(String.valueOf(arr[1]));
                t2.setBackgroundResource(R.drawable.shape_input_ok);
            } else if (i == 2) {
                t3.setText(String.valueOf(arr[2]));
                t3.setBackgroundResource(R.drawable.shape_input_ok);
            } else if (i == 3) {
                t4.setText(String.valueOf(arr[3]));
                t4.setBackgroundResource(R.drawable.shape_input_ok);
                if(key.equals(code)){
                    //验证码正确
                    myHandler.sendEmptyMessage(1);
                    yzmdialog.dismiss();
                    getCode();
                }else{
                    //验证码错误
                    toastShow("验证码错误,请重试");
                }
            }
        }
    }

    TextWatcher tw = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            key = s.toString();
            setKey();
        }
    };
}
